import permision from '@/js_sdk/wa-permission/permission.js'

class VoiceRecorderNative {
  constructor() {
    this.audioRecorder = uni.requireNativePlugin?.('audio-recorder')
    this.permisionID = 'android.permission.RECORD_AUDIO'
    this.isRecording = false
    this.stopCallback = null

    this.AudioPath = ''
    this.Environment = plus.android.importClass('android.os.Environment')
    this.File = plus.android.importClass('java.io.File')
    this.main = plus.android.runtimeMainActivity()

    this.initFiles()
  }

  /**
   * 初始化音频存储路径
   * 优先使用外部存储，不可用时回退到内部存储
   */
  initFiles() {
    if (
      this.Environment.MEDIA_MOUNTED ||
      !this.Environment.isExternalStorageRemovable()
    ) {
      this.AudioPath =
        this.main.getExternalFilesDir(null).getPath() + '/recorders'
      this.AppPath = this.main.getExternalFilesDir(null).getPath()
    } else {
      this.AudioPath = this.main.getFilesDir().getPath() + '/recorders'
      this.AppPath = this.main.getFilesDir().getPath()
    }
    console.log('文件存放路径=>', this.AudioPath)
  }

  // 请求录音权限
  requestRecordPermission() {
    return new Promise(async (resolve, reject) => {
      const result = await permision.requestAndroidPermission(this.permisionID)
      if (result !== 1) {
        uni.showModal({
          title: '权限申请',
          content: '需要麦克风权限才能进行录音',
          success: res => {
            if (res.confirm) {
              console.log('用户确认授权')
              permision.gotoAppPermissionSetting()
            } else {
              console.log('用户拒绝授权')
              // 显示错误提示
              uni.showToast({
                title: '用户拒绝授权',
                icon: 'none',
                duration: 3000
              })
              reject(new Error('用户拒绝授权'))
            }
          }
        })
      } else {
        resolve()
      }
    })
  }

  // 开始录音
  start() {
    const savefilePath =
      this.AudioPath + '/recorder_audio_' + Date.now() + '.aac'
    // 先请求录音权限
    this.requestRecordPermission()
      .then(() => {
        this.audioRecorder.start(
          savefilePath,
          startResult => {
            console.log('🎤 录音开始')
            this.isRecording = true
            console.log(startResult)
          },
          stopResult => {
            console.log(stopResult)
            console.log('⏹️ 录音停止')
            this.isRecording = false
            if (stopResult.filePath) {
              console.log('录音文件路径:', stopResult.filePath)
            }
            if (this.stopCallback) {
              this.stopCallback(stopResult)
            }
            // 删除旧的音频文件
            this.deleteOldLogFiles()
          },
          error => {
            this.isRecording = false
            this.audioRecorder.stop()
            console.log(error)
          }
        )
      })
      .catch(err => {
        console.error('录音权限获取失败:', err)
      })
  }

  // 停止录音
  stop() {
    if (this.isRecording) {
      this.audioRecorder.stop()
    }
  }

  onStop(callback) {
    this.stopCallback = callback
  }

  // 删除超过一定数量的旧音频文件
  deleteOldLogFiles(maxFileCount = 15) {
    let logFiles = this.getLogFileList()
    // 按照最后修改时间排序
    logFiles.sort(function (a, b) {
      return b.updateTime - a.updateTime
    })
    console.log('总音频文件=>', logFiles)
    if (logFiles.length > maxFileCount) {
      for (let i = maxFileCount; i < logFiles.length; i++) {
        this.removeLogFile(logFiles[i].filePath)
      }
    }
  }

  /**
   * 删除指定音频文件
   * @param {string} filePath - 要删除的文件路径
   */
  removeLogFile(filePath) {
    const file = new this.File(filePath)
    const fos = new this.FileOutputStream(filePath, true)
    fos.close()
    file.delete()
    console.log('删除文件=>', filePath)
  }

  /**
   * 删除所有音频文件
   */
  removeAllLogFile() {
    const logFiles = this.getLogFileList()
    for (let i = 0; i < logFiles.length; i++) {
      this.removeLogFile(logFiles[i].filePath)
    }
  }

  /**
   * 获取音频文件列表
   * @returns {Array} 返回包含文件名和路径的对象数组
   */
  getLogFileList() {
    const list = []
    const file = new this.File(this.AudioPath)
    const tempList = file.listFiles()

    for (let i = 0; i < tempList.length; i++) {
      list.push({
        index: i,
        name: tempList[i].getName(),
        filePath: tempList[i].getPath(),
        size: tempList[i].length(),
        updateTime: tempList[i].lastModified()
      })
    }

    return list
  }
}

export default new VoiceRecorderNative()
